<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cart in cartList" :key="cart.cartid">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="cart.cartState == 1"
              @click="updateChecked(cart, $event)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cart.wares.pictureList[0]" />
            <div class="item-msg">
              {{ cart.wares.waresName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cart.wares.waresPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a v-throttle class="mins" @click="handler('minus', -1, cart)">-</a>
            <input
              autocomplete="off"
              type="text"
              :value="cart.waresNumber"
              minnum="1"
              class="itxt"
              @change="handler('change', $event.target.value * 1, cart)"
            />
            <a v-throttle class="plus" @click="handler('add', 1, cart)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cart.waresNumber * cart.wares.waresPrice }}</span>
          </li>
          <li class="cart-list-con7">
            <a class="sindelet" @click="deleteCartById(cart)"
              >删除</a
            ><br/>
            <a class="sindelet" @click="addCollectById(cart)"
              >收藏</a
            >
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input
          class="chooseAll"
          type="checkbox"
          :checked="isAllCheck"
          @change="updateAllCartChecked"
        />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="deleteAllCheckedCart">删除选中的商品</a>
        <a @click="cartToCollect">收藏选中商品</a>
        <a @click="clearCart">删除被冻结或已下架商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择<span>{{checkNmuber}}</span>件商品</div>
        <div class="sumprice">
          <em>总价: </em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" @click="cartToOrder">结算</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "ShopCart",
  data() {
    return {
      isLock: false, // 控制按钮的disable属性
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    //获取个人购物车列表
    getData() {
      this.$store.dispatch("getCartList");
    },
    //删除全部选中的商品
    async deleteAllCheckedCart() {
      try {
        await this.$store.dispatch("deleteAllCheckedCart");
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    //删除一个产品
    async deleteCartById(cart) {
      try {
        await this.$store.dispatch("deleteCartByWaresId", cart.cartId);
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    //删除已下架或被冻结商品
    async clearCart() {
      try {
        await this.$store.dispatch("clearCart");
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    //修改全部产品的选中状态
    async updateAllCartChecked(event) {
      let cartState = event.target.checked ? "1" : "0";
      try {
        await this.$store.dispatch("updateAllCartChecked", cartState);
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    //修改一个产品的选中状态
    async updateChecked(cart, event) {
      let cartState = event.target.checked ? "1" : "0";
      console.log(cart.waresId);
      console.log(cartState);
      try {
        await this.$store.dispatch("updateCheckerById", {
          waresId: cart.waresId,
          cartState: cartState,
        });
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    //修改某一个产品的个数
    async handler(type, disNum, cart) {
      //type:区分点击的元素
      //disNum：代表输入的变化量或最终值,
      //cart:帮助传入商品的id
      switch (type) {
        case "add":
          //带给服务器变化量
          disNum = 1;
          break;
        case "minus":
          //产品数大于1传-1否则数据不动
          disNum = cart.waresNumber > 1 ? -1 : 0;
          break;
        case "change":
          //如果输入值非法,值不变
          disNum =
            isNaN(disNum) || disNum < 1 ? 0 : parseInt(disNum) - cart.waresNumber;
          break;
      }
      try {
        //修改成功
        await this.$store.dispatch("addOrUpdateShopCart", {
          waresId: cart.wares.waresId,
          waresNum: disNum,
        });
        //再次获取数据
        this.getData();
      } catch (error) {
        alert("失败")
      }
    },
    //跳转到提交页面
    async cartToOrder() {
      try {
        // await this.$store.dispatch("insertCartToOrder");
        this.$router.push({path:"/trade"})
      } catch (error) {
        alert(error.message);
      }
    },
    //提交购物车选中商品到收藏
    async cartToCollect() {
      try {
        await this.$store.dispatch("insertCartToCollect");
        this.$router.push({path:"/center/mycollect"})
      } catch (error) {
        alert(error.message);
      }
    },
    //收藏一个产品
    async addCollectById(cart) {
      try {
        await this.$store.dispatch("addCollect", {waresId:cart.waresId});
      } catch (error) {
        alert(error.message);
      }
    },
  },
  computed: {
    ...mapGetters(["cartList"]),
    //计算产品购买总价
    totalPrice() {
      let sum = 0;
      this.cartList.forEach((item) => {
        sum += item.waresNumber * item.wares.waresPrice;
      });
      return sum;
    },
    //判断底部复选框是否全部勾选
    isAllCheck() {
      //遍历数组
      return this.cartList.every((item) => item.cartState == 1)&& this.cartList.length > 0;
    },
    checkNmuber(){
      let sum=0;
      this.cartList.forEach((item) => {
        if(item.cartState==1){
          sum++;
        }
      });
      return sum;
    }
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      & > div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        & > li {
          float: left;
        }

        .cart-list-con1 {
          width: 15%;
        }

        .cart-list-con2 {
          width: 35%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con3 {
          width: 20.8333%;

          .item-txt {
            text-align: center;
          }
        }

        .cart-list-con4 {
          width: 10%;
        }

        .cart-list-con5 {
          width: 17%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
</style>